package com.cr.admin.business.authentication.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cr.admin.business.audit.pojo.dto.AuditSaveParam;
import com.cr.admin.business.audit.service.AuditService;
import com.cr.admin.business.authentication.mapper.AuthenticationMapper;
import com.cr.admin.business.authentication.pojo.dto.param.AuthenticationSaveParam;
import com.cr.admin.business.authentication.pojo.dto.param.AuthenticationUpdateParam;
import com.cr.admin.business.authentication.pojo.dto.query.AuthenticationQuery;
import com.cr.admin.business.authentication.pojo.entity.Authentication;
import com.cr.admin.business.authentication.pojo.vo.AuthenticationVO;
import com.cr.admin.business.authentication.service.AuthenticationService;

import com.cr.common.exception.ServiceException;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
@Service
@Slf4j
public class AuthenticationServiceImpl implements AuthenticationService {
    @Autowired
    private AuthenticationMapper authenticationMapper;
    @Autowired
    private AuditService auditService;
    @Override
    public void addAuthentication(AuthenticationSaveParam authenticationSaveParam) {
        log.warn("入参{}",authenticationSaveParam);
        long userId = authenticationSaveParam.getUserId();

        Authentication authentication = new Authentication();
        BeanUtils.copyProperties(authenticationSaveParam, authentication);

        //yyyy-mm-dd格式字符串转date
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date validStart = null;
        Date validEnd = null;
//        Date birthday = null;
        try {
            validStart = sdf.parse(authenticationSaveParam.getValidDateStart());
            validEnd = sdf.parse(authenticationSaveParam.getValidDateEnd());
//            birthday = sdf.parse(authenticationSaveParam.getBirthday());
            //设置出生日期
//            authentication.setBirthday(birthday);

        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        Date now = new Date();
        //证件是否有效
        if(validEnd.after(now) && now.after(validStart)){
            authentication.setStatus(0);
            authentication.setValidDateStart(validStart);
            authentication.setValidDateEnd(validEnd);
        }else{
            throw new ServiceException("证件有效日期错误");

        }
        //设置审核中
        authentication.setAuditing(1);
        //使同类型的证件标注未选中
        Integer authenticationType = authenticationSaveParam.getAuthenticationType();
        checkDuplicateAuthentication(userId, authenticationType);
        //选中新增的证件
        authentication.setSelection(0);
        authentication.setApplicationId(generateUniqueOrderNumber());
        authenticationMapper.insert(authentication);
        AuditSaveParam auditSaveParam = new AuditSaveParam();
        auditSaveParam.setApplicationId(authentication.getApplicationId());
        auditService.addAuthenticationAudit(auditSaveParam);

    }

    @Override
    public AuthenticationVO getAuthenticationDetail(Long id) {

        AuthenticationVO authenticationVO =new AuthenticationVO();

        Authentication authentication = authenticationMapper.selectById(id);
        BeanUtils.copyProperties(authentication, authenticationVO);
        return authenticationVO;
    }

    @Override
    public List<AuthenticationVO> list(AuthenticationQuery authenticationQuery) {
        List<AuthenticationVO> authenticationVOS = new ArrayList<>();
        QueryWrapper<Authentication> queryWrapper = new QueryWrapper<>();
        if(authenticationQuery.getStatus()!=null){
            queryWrapper.eq("status", authenticationQuery.getStatus());
        }
        if(authenticationQuery.getAuditing()!=null){
            queryWrapper.eq("auditing", authenticationQuery.getAuditing());
        }
        if(authenticationQuery.getSelection()!=null){
            queryWrapper.eq("selection",authenticationQuery.getSelection());
        }
        List<Authentication> authentications = authenticationMapper.selectList(queryWrapper);
        for(Authentication authentication : authentications){
            AuthenticationVO authenticationVO = new AuthenticationVO();
            BeanUtils.copyProperties(authentication, authenticationVO);
            authenticationVOS.add(authenticationVO);
        }

        return authenticationVOS;
    }

    @Override
    public void updateById(AuthenticationUpdateParam authenticationUpdateParam) {
//        Authentication authentication = new Authentication();
//        BeanUtils.copyProperties(authenticationUpdateParam, authentication);
        UpdateWrapper<Authentication> updateWrapper= new UpdateWrapper<>();
        updateWrapper.eq("id", authenticationUpdateParam.getId());
        updateWrapper.set("auditing", authenticationUpdateParam.getAuditing());
        authenticationMapper.update(null,updateWrapper);
    }
    @Override
    public void deleteByIds(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            throw new ServiceException("参数不能为空");
        }
        authenticationMapper.deleteBatchIds(ids);
        //删除审核记录 TODO

    }

    private void checkDuplicateAuthentication(Long userId, Integer authenticationType){
        UpdateWrapper<Authentication> updateWrapper= new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId);
//        updateWrapper.eq("authentication_type",authenticationType);
        updateWrapper.set("selection",1);
        authenticationMapper.update(null, updateWrapper);

    }

    private String generateUniqueOrderNumber() {
        // 这里可以根据业务需求生成唯一的订单号，例如使用数据库的序列、UUID、时间戳+随机数等方式生成
        Random random = new Random();
        long currentTime = System.currentTimeMillis();
        long orderNumber = currentTime * 1000 + random.nextInt(1000); // 保证足够唯一性
        return String.valueOf(orderNumber);
    }
}
